var config = require('common/config');
var shihan = require('common/fetch');
App({
  data: {
    deviceInfo: {},
    isNavigating: false,
    partnerflag: 0,
    is_refresh_shopping: 0,
    setupdownloadimgflag: 1
  },
  onLaunch: function() {
    this.data.deviceInfo = wx.getSystemInfoSync();
  },
  wechatSwitch: function() {
    return new Promise(function(resolve, reject) { //other_config
      shihan.sendRequest(config.other_config, 'POST', {})
        .then(function(response) {
          if (response.data.code == 0) {
            config.wechat_switch = response.data.data.sh_wechat_test_switch
            // config.wechat_switch = 0
          } else {
            config.wechat_switch = 0
          }
          resolve(config.wechat_switch);
        }, function(error) {
          console.log(error);
          reject(config.wechat_switch);
        });
    })
  },
  commonLogin: function(sceneres, wechat_switch) {
    var that = this
    var token = wx.getStorageSync('token');

    if (sceneres.cid) {
      config.cid = sceneres.cid;
    }
    if (sceneres.partner_id) {
      config.partner_id = sceneres.partner_id;
    }

    if (wechat_switch == 1) { //是否打开微信授权开关
      that.getUserInfo(sceneres)
    } else {
      if (token) { //有token，已注册用户
        shihan.sendRequest(config.check_login, 'POST', {})
          .then(function(response) { //执行登录校验
            if (response.data.code == 0) {
              if (response.data.data) {
                wx.setStorageSync('customerId', response.data.data)
              } else { //token已过期
                wx.setStorageSync('token', '');
                wx.navigateTo({
                  url: '/pages/userauthor/userauthor',
                })
              }
            } else if (response.data.code == 1101) {
              wx.setStorageSync('token', '');
              wx.navigateTo({
                url: '/pages/userauthor/userauthor',
              })
            } else { //接口请求失败，未知原因
              wx.showModal({
                title: '提示',
                content: response.data.msg,
                confirmText: "确认",
                confirmColor: "#c40000",
                showCancel: false,
                success: function (res) {
                  wx.navigateTo({
                    url: '/pages/userauthor/userauthor',
                  })
                }
              })
            }
          }, function(error) {})
      } else {
        wx.setStorageSync('token', '');
        wx.navigateTo({
          url: '/pages/userauthor/userauthor',
        })
      }
    }
  },
  getUserInfo: function(sceneres) {
    //调起微信授权
    var that = this
    wx.login({
      success: function(res) {
        var code = res.code;
        wx.getUserInfo({
          success: function(resinfo) {
            sceneres.code = code;
            sceneres.iv = resinfo.iv;
            sceneres.user_json = resinfo.rawData;
            sceneres.encryptedData = resinfo.encryptedData;
            that.wechatLogin(sceneres)
          },
          fail: function(res) { //用户拒绝授权时弹窗
            console.log(res)
            var token = wx.getStorageSync('token');
            if (!token) {
              wx.navigateTo({
                url: '/pages/userauthor/userauthor',
              })
            }
          }
        })
      }
    })
  },
  wechatLogin: function(sceneres) {

    var data = {};
    data["userinfo_code"] = sceneres.code;
    data["iv"] = sceneres.iv;
    data["encrypted_data"] = sceneres.encryptedData;
    data['user_json'] = sceneres.user_json; //用户信息
    data["channel_id"] = config.cid;
    data["partner_id"] = config.partner_id;


    // console.log(data); //打印参数信息

    shihan.sendRequest(config.wechatLogin, 'POST', data)
      .then(function(response) { //执行登录,获取用户信息
        if (response.data.code == 0) {

          wx.setStorageSync('open_id', response.data.data.sh_open_id); //open_id,authbind接口需要校验
          wx.setStorageSync('customerId', response.data.data.sh_customer_id); //用户ID，
          wx.setStorageSync('token', response.data.data.sh_token); //用户登录凭证token

        } else if (response.data.code == 1101) {
          wx.setStorageSync('token', '');
          wx.navigateTo({
            url: '/pages/userauthor/userauthor',
          })

        } else { //接口请求失败，未知原因
          wx.showModal({
            title: '提示',
            content: response.data.msg,
            confirmText: "确认",
            confirmColor: "#c40000",
            showCancel: false,
            success: function (res) {
              wx.navigateTo({
                url: '/pages/userauthor/userauthor',
              })
            }
          })
        }
      }, function(error) {})
  },
  commonNoLogin: function() {
    wx.setStorageSync('token', '');
    wx.navigateTo({
      url: '/pages/userauthor/userauthor',
    })
  },
  moniLogin: function(sceneres, e) { //模拟用户信息授权
    var that = this
    if (!e.detail.encryptedData) {
      that.commonNoLogin()
      return
    }
    wx.login({
      success: function(res) {
        sceneres.code = res.code;
        sceneres.iv = e.detail.iv;
        sceneres.user_json = e.detail.rawData;
        sceneres.encryptedData = e.detail.encryptedData;
        that.wechatLogin(sceneres)
      }
    })
  },
  submissionForm: function(formid, num, obj) { //表单提交
    /*
      form_id: 小程序form表单id
      send_limit: 小程序推送条数 微信支付3条（支付是，不用表单id，使用prepayid.split('=')[1]）， 普通表单1条
      send_obj: 推送类别 1-新绑定手机号用户， 2-领券用户， 3-下单用户  4-微信支付用户   5-单个指定用户
    */ 
    if (formid&&formid.indexOf('formId') < 0) {
      shihan.sendRequest(config.add_wx_form, 'POST', {
          form_id: formid,
          send_limit: num,
          send_obj: obj
        })
        .then(function(response) {
          if (response.data.code == 0) {
            console.log(response)
          }
        }, function(error) {});
    }
  },
  AdSkipper: function(e, stage) { //广告位跳转
    var adverttype = e.currentTarget.dataset.type
    if (e.currentTarget.dataset.url && adverttype != 'product' && adverttype != 'seller') {
      adverttype = e.currentTarget.dataset.url
    }
    var advertid = e.currentTarget.dataset.id
    var advertname = e.currentTarget.dataset.name || '';
    if (adverttype && adverttype.indexOf('http://') == 0) {
      var paramurl = adverttype.split('//')[1].split('='); //http://product=26  此种参数配置已废弃
      if (paramurl.length > 0) {
        adverttype = paramurl[0]
        advertid = paramurl[1]
      }
    }
    if (adverttype && adverttype.indexOf('https://') == 0) { //参数是url地址时，跳转小程序web-view容器
      if (adverttype && adverttype.indexOf('cooperation') > 0) { //合作伙伴需要使用小程序页面
        wx.navigateTo({
          url: '/pages/other/cooperation/cooperation',
        })
      } else {
        wx.navigateTo({
          url: '/pages/strategyinfo/strategyinfo?url=' + encodeURIComponent(adverttype) + '&name=' + advertname
        })
      }
    }

    switch (String(adverttype)) {
      case 'product':
        wx.navigateTo({
          url: '/pages/goodsdetail/goodsdetail?goodsid=' + advertid
        })
        break; //商品详情
      case 'seller':
        wx.navigateTo({
          url: '/pages/storedetail/storedetail?id=' + advertid
        })
        break; //店铺详情
      case 'category':
        wx.navigateTo({
          url: '/pages/categoryDetail/categoryDetail?type=0&topcid=' + advertid + '&cid=&bid='
        })
        break; //品类二级详情页面
      case 'group_buy':
        wx.navigateTo({
          url: '/pages/other/groupbuy/groupbuy'
        })
        break; //拼团首页列表
      case 'agent':
        wx.navigateTo({
          url: '/pages/business/index/index'
        })
        break; //微商联盟
      case 'open_event':
        wx.navigateTo({
          url: '/pages/other/eventopen/eventopen'
        })
        break; //联盟商家促销活动主页
    }
  },
  getCity: function(cb) {
    var that = this
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        var locationParam = res.latitude + ',' + res.longitude + '1'
        wx.request({
          url: 'https://api.map.baidu.com/geocoder/v2/',
          data: {
            ak: 'guH7F9WWuyz1rrg5S8xoFOoDbdf8wipp',
            location: locationParam,
            output: 'json',
            pois: '1'
          },
          method: 'GET',
          success: function(res) {
            config.city = decodeURIComponent(res.data.result.addressComponent.city)
            config.province = decodeURIComponent(res.data.result.addressComponent.province)
            typeof cb == "function" && cb(res.data.result.addressComponent.city.slice(0, -1))
          },
          fail: function(res) {
            // 重新定位
            that.getCity();
          }
        })
      }
    })
  }
})